package com.epam.player.desktop.logic;

import java.io.IOException;

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

import org.apache.log4j.Logger;

import com.epam.player.vkapi.model.Song;

public class MP3PlayerManager {
	
	final static Logger LOG = Logger.getLogger(MP3PlayerManager.class);
	
	private Player player;
	private Thread thread;

	public synchronized void play(final Song song) {
		thread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					LOG.info("Playing...[" + song + "]");
					player = new Player(song.getUrl().openStream());
					player.play();
				} catch (JavaLayerException e) {
					stop();
				} catch (IOException e) {
					stop();
				}
			}

		});
		thread.start();
		thread.setName("MP3PlayerController: Playing...");

	}

	public synchronized void stop() {
		if (player != null) {
			LOG.info("Stop playing");
			player.close();
			thread.stop();
		}
	}

	public synchronized int getCurrentPosition() {
		if (player != null) {
			return player.getPosition();
		}
		return 0;
	}

	public synchronized boolean isComplete() {
		if (player != null) {
			return player.isComplete();
		}
		return false;
	}
}
